package com.housediyadmin.view.components.Renterer
{
	import com.housediyadmin.model.PicModel;
	
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.net.FileReference;
	
	import mx.controls.ProgressBar;
	import mx.events.FlexEvent;
	
	import org.robotlegs.mvcs.Mediator;
	
	/**
	 * 
	 * @author liaoruohuai
	 * 
	 */
	public class UploadRendererMediator extends Mediator
	{
		[Inject]
		public var view:UploadRenderer;
		
		[Inject]
		public var model:PicModel;
		
		override public function onRegister():void
		{	
			view.progressBar.addEventListener(FlexEvent.CREATION_COMPLETE, initProgressBar);
			view.cancelButton.addEventListener(MouseEvent.CLICK, cancelUpload);
			view.deleteButton.addEventListener(MouseEvent.CLICK, deletePic);
		}
		
		public function initProgressBar(e:Event):void
		{
			var pb: ProgressBar = e.target as ProgressBar;											
			pb.label = "%3%%";											
			pb.setProgress(0, 100);											
			var f: FileReference = view.data as FileReference;											
			//使用闭包方法，更新进度条											
			f.addEventListener(ProgressEvent.PROGRESS,											
				function(event: ProgressEvent): void												
				{												
					pb.setProgress(event.bytesLoaded, event.bytesTotal);													
				}												
			);
			f.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,											
				function (event: DataEvent): void												
				{																								
					pb.label = event.data;													
				}
			);           
		}
		
		public function cancelUpload(e:Event):void
		{
			var f: FileReference = view.data as FileReference;										
			f.cancel();	
		}
		
		public function deletePic(e:Event):void
		{
			var f: FileReference = view.data as FileReference;										
			removeFile(f);
		}
		
		public function removeFile(f: FileReference): void				  
		{					
			var index: int = model.selectedFiles.getItemIndex(f);
			if (index != -1)						
				model.selectedFiles.removeItemAt(index);	
		}	
	}
}